Random¶

🖌 random¶

NOTES

  • For each example, demonstrate how running the code again yields different results

random.choice()¶

In [13]:
import random

fruits = ['pear','mango','banana','strawberry','kumquat']
selection = random.choice(fruits)
print(selection)
mango

random.randint()¶

In [41]:
import random

print(random.randint(1, 10))
2

NOTES

  • Note that random.randint() can return the boundary numbers
    • so, the return number is anything including and between the arguments.

random.random()¶

In [77]:
print(random.random())
0.5803070027788184

If you need a random float between 0 and 100, just scale the random number:

In [95]:
print(random.random() * 100)
40.015655234506866

random.sample()¶

In [96]:
name = 'George Washington'
In [102]:
print(random.sample(name, 2))
['r', 'G']
In [110]:
print(random.sample(name, 10))
['o', 'n', 'i', 'e', 's', 't', ' ', 'a', 'n', 'g']
In [130]:
print(''.join(random.sample(name, len(name))))
sW nieGgerognaoth

🖌 Shuffle¶

random.sample can be used to get a random sample from a collection.

If you sample all the items in the collection, you essentially get a shuffled version of the data.

In [131]:
import random

def shuffle(string):
    """
    Use random.sample to get the letters in the string in a random order.
    Then join the letters together with the empty string.
    """
    shuffled_letters = random.sample(string, len(string))
    return ''.join(shuffled_letters)
In [137]:
shuffle('12345')
Out[137]:
'32154'
In [151]:
shuffle('CS110')
Out[151]:
'1CS10'

🖌 Random events at some frequency¶

apples.py¶

🧑🏼‍🎨 Umm...¶

Write a program that takes a frequency (a number between 0 and 1) and a phrase as commandline arguments.

Randomly inject "umm" into a given sentence at the given frequency and print the result.

umm.py¶

NOTES

  • Draw it out!
    • Sentence -> words -> words with umm -> sentence
python umm.py 0.2 'So, I've been meaning to ask, will you go out on a date with me?'

👨🏻‍🎨 Random¶

  • 2-player guessing game
  • Bit: fill world with random colors
  • Bit: random walk to target

Key Ideas¶

  • random
    • choice
    • randint
    • random
    • sample
  • Shuffling strings using random.sample
  • Random events at some frequency